package netty.tcpbug.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Huhailong
 * @Description
 * @Date 2021/4/12.
 */
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    private int counter;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        ByteBuf buf = (ByteBuf) msg;
//        byte[]req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
        //System.getProperty("line.separator") 获取对应操作系统下的换行符
//        String body = new String(req, StandardCharsets.UTF_8).substring(0,req.length-System.getProperty("line.separator").length());

        //使用netty解决粘包问题
        String body = (String)msg;
        System.out.println("The time server receive order : "+body+" ; the counter is : "+(++counter));
        String currentTime = "QUERY CURRENT TIME".equalsIgnoreCase(body)?LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")):"BAD QUERY";
        currentTime = currentTime+System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.write(resp);    //将响应消息放到发送缓冲区中
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();    //将发送缓冲区的消息全部写道SocketChannel中
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
